package com.duowei.diandan.util;


import android.support.v7.app.AlertDialog;
import android.widget.Toast;

import com.duowei.diandan.BuildConfig;
import com.duowei.diandan.R;
import com.duowei.diandan.activity.BaseActivity;
import com.duowei.diandan.bean.Update;
import com.duowei.diandan.fragment.dialog.UpdateFragment;
import com.google.gson.Gson;

public class UpdateHelper {
    private BaseActivity mActivity;

    public UpdateHelper(BaseActivity activity) {
        mActivity = activity;
    }

    public void checkUpdate() {
        String url = "http://androidwww.wxdw.top:2233/androidauth/app/diandan2.txt";
        NetUtils.get(url, new GetListener() {
            @Override
            public void onFail(Exception e) {
            }

            @Override
            public void onSuccess(String result) {
                //noinspection EmptyCatchBlock
                try {
                    Update update = new Gson().fromJson(result, Update.class);

                    if (update.getVersionCode() > BuildConfig.VERSION_CODE) {
                        updateDialog(update);
                    } else {
                        Toast.makeText(mActivity, "未发现新版本更新", Toast.LENGTH_SHORT).show();
                    }

                } catch (Exception e) {
                }
            }
        });
    }

    private void updateDialog(Update update) {
        mActivity.runOnUiThread(() -> {
            AlertDialog.Builder builder = new AlertDialog.Builder(mActivity);
            builder.setCancelable(false);
            builder.setIcon(R.mipmap.ic_launcher);
            builder.setTitle("检测到新版本，是否升级？");
            builder.setMessage(update.getMsg());

            builder.setNegativeButton("取消", null);
            builder.setPositiveButton("升级", (dialogInterface, i) -> {
                UpdateFragment fragment = UpdateFragment.newInstance(update.getUrl(), update.getName());
                fragment.show(mActivity.getSupportFragmentManager(), "升级");
            });
            builder.show();
        });
    }
}
